require 'simply_mongo'
module SimplyMongo

  Rails.application.config.after_initialize do
    mongo_config_file = File.join("#{Rails.root}", 'config', 'mongo.yml')
    raise "#{mongo_config_file} is missing!" unless File.exists? mongo_config_file
    mongo_config = YAML.load_file(mongo_config_file)

    db_config = mongo_config.fetch(Rails.env)

    db_name = db_config['database']
    raise "Mongo database not set for environment #{Rails.env}" unless not db_name.nil?

    host = db_config['host']
    if host.nil? then
      host = localhost
    end

    port = db_config['port']
    if port.nil? then
      port = 27017
    end

    options = db_config['options']
    if options.nil?
      options = {}
    end

    @@driver = SimplyMongo::Driver.new(db_name, host, port, options.symbolize_keys);
    @@connection = @@driver.conn
    @@db = @@driver.db
  end
  
  def SimplyMongo.db
    @@db
  end
  
  def SimplyMongo.connection
    @@connection
  end
  
  def SimplyMongo.driver
    @@driver
  end
end


